<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ngannv
 * Date: 3/8/12
 * Time: 5:56 PM
 * To change this template use File | Settings | File Templates.
 */
define('WRITE_LOG',1);
define('LOG_PATH','_log/');
class eLogs
{

    /**
     * Object configure
     */
    //Ghi log DB
    private static $instance = null;

    /**
     * constructor method
     */
    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new eLogs();
        }
        return self::$instance;
    }

    static function CheckDir($pDir)
    {
        if (is_dir($pDir))
            return true;
        if (!@mkdir($pDir, 0777, true)) {
            return false;
        }
        self::chmod_dir($pDir, 0777);
        return true;
    }

    static function chmod_dir($dir, $mod = 0777)
    {
        $parent_dir = dirname(str_replace(ROOT_PATH, '', $dir));
        if ($parent_dir != '' && $parent_dir != '.') {
            @chmod($dir, $mod);
            self::chmod_dir($parent_dir, $mod);
        }
        return true;
    }

    public static function writeLogFile($data, $logFilePrefix = '', $aryFormat = null)
    {
        if (WRITE_LOG) {
            if ($aryFormat == null) {
                $logFormat = '[%s][%s][%s][%s]';
                $user      = '';
                /*                if (User::is_login()) {
                    $user = 'User:' . User::$current['staff_account'] . '-ID: ' . User::id() . '-FullName:' . User::$current['staff_name'];
                } else {
                    $user = 'Guest';
                }*/
                $logData = sprintf($logFormat, $_SERVER['REMOTE_ADDR'], $user, date('Y-m-d H:i:s', TIME_NOW), $data);
            }
            elseif (is_array($aryFormat)) {
                $logFormat = '[%s][%s][%s][%s]%s[FILE: %s][LINE: %d]';
                $logData   = sprintf($logFormat, $_SERVER['REMOTE_ADDR'], date('Y-m-d H:i:s', TIME_NOW), $aryFormat[0], $data, $aryFormat[1], $aryFormat[2]);
            }
            $subDir = LOG_PATH . date('Y_m_d/H');
            self::CheckDir($subDir);
            $logFile = realpath($subDir) . '/' . $logFilePrefix . '.log.txt';
            if (!file_exists($logFile)) {
                $file = @fopen($logFile, 'w+');
                fclose($file);
            }
            if (!is_writable($logFile)) {
                @chmod($logFile, 0400);
            }
            $logData .= "\n\n";
            error_log($logData, 3, $logFile);

        }
    }

}

